<template>
  <div class="user-info">
    <van-nav-bar
      title="个人信息"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <div class="container">
      <div class="avatar">
        <van-uploader :after-read="uploadFile">
          <img :src="userInfo.avatar || resources.defaultAvatar" alt="" />
        </van-uploader>
      </div>
      <van-cell-group inset>
        <van-cell title="用户名" :value="userInfo.username" />
        <van-cell title="昵称" :value="userInfo.nickname" />
        <van-cell title="手机号" :value="userInfo.phone" />
        <van-cell title="创建时间" :value="formatDate(userInfo.createTime)" />
      </van-cell-group>
    </div>
    <div class="btn">
      <van-button type="info" round block @click="show = true"
        >修改信息</van-button
      >
    </div>
    <!-- 修改信息 -->
    <van-popup
      v-model:show="show"
      round
      closeable
      position="bottom"
      :style="{ height: '46%' }"
    >
      <div class="form">
        <h3>修改信息</h3>
        <van-form ref="form">
          <van-cell-group inset class="item">
            <van-field
              class="item-field"
              v-model="copyInfo.nickname"
              label="昵称"
              :clearable="true"
              placeholder="请输入昵称"
              :rules="[{ required: true, message: '请输入昵称' }]"
            />
          </van-cell-group>
          <van-cell-group inset class="item">
            <van-field
              class="item-field"
              v-model="copyInfo.phone"
              label="手机号"
              :clearable="true"
              placeholder="请输入手机号"
              :rules="[
                { required: true, message: '请输入手机号' },
                { pattern: /^1[3456789]\d{9}$/, message: '手机号格式不正确' },
              ]"
            />
          </van-cell-group>
          <van-cell-group inset class="item">
            <van-button type="primary" block round @click="updateUserInfo"
              >提交</van-button
            >
          </van-cell-group>
        </van-form>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { uploadFile } from "@/api/common/common";
import { getUserInfo, updateUserInfo } from "@/api/mobile/user";
import modifyActivityTime from "@/utils/modify";
import userModule from "@/utils/userInfo";
import { Notify } from "vant";
import { getList } from "@/api/mobile/resources";
export default {
  name: "UserInfoView",
  data() {
    return {
      userInfo: {},
      copyInfo: {},
      show: false,
      resources: {},
    };
  },
  created() {
    this.getUserInfo();
    this.getResources();
  },
  methods: {
    async getResources() {
      const res = await getList();
      this.resources = res.data;
    },
    // 获取用户信息
    async getUserInfo() {
      const user = userModule.getUser();
      const res = await getUserInfo({ id: user.id });
      this.userInfo = res.data;
      this.copyInfo = { ...res.data };
      // 更新用户活动时间
      modifyActivityTime();
    },
    // 修改用户信息
    async updateUserInfo() {
      await this.$refs.form.validate();
      const { username, ...data } = this.copyInfo;
      const res = await updateUserInfo(data);
      Notify({ type: "success", message: res.msg });
      this.show = false;
      this.getUserInfo();
    },
    // 上传文件
    async uploadFile({ file }) {
      // 判断格式是否正确;
      const bool = this.verifyFormat(file);
      if (!bool) {
        return;
      }
      // 上传到服务器;
      let formData = new FormData();
      // 拿到存在file中的文件存放到formData中
      formData.append("file", file);
      const res = await uploadFile(formData);
      await updateUserInfo({
        id: this.userInfo.id,
        avatar: res.data,
        originalAvatar: this.userInfo.avatar,
      });
      Notify({ type: "success", message: res.msg });
      await this.getUserInfo();
      // 更改本地存储信息
      const { id, nickname, avatar } = this.userInfo;
      userModule.setUser({
        id,
        nickname,
        avatar,
      });
    },
    // 上传封面前校验格式
    verifyFormat(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isJPG) {
        Notify({
          type: "warning",
          message: "上传头像图片只能是 jpg/jpeg/png 格式!",
        });
        return false;
      }
      if (!isLt5M) {
        Notify({
          type: "warning",
          message: "上传头像图片大小不能超过 5MB!",
        });
        return false;
      }
      return isJPG && isLt5M;
    },
    // 时间格式判断
    padZero(num) {
      return num < 10 ? "0" + num : num;
    },
    // 时间格式化
    formatDate(timeArray) {
      if (!timeArray) return "暂无时间";
      let year = timeArray[0];
      let month = this.padZero(timeArray[1]);
      let day = this.padZero(timeArray[2]);
      let hour = this.padZero(timeArray[3]);
      let minute = this.padZero(timeArray[4]);
      let second = this.padZero(timeArray[5]) || "00";
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },
  },
};
</script>

<style lang="less" scoped>
.user-info {
  position: relative;
  min-height: 100vh;
  .container {
    .avatar {
      margin: 20px auto;
      width: 70px;
      height: 70px;
      border-radius: 50%;
      border: 1px solid #ccc;
    }
  }
  .btn {
    position: absolute;
    bottom: 20px;
    width: 90%;
    left: 50%;
    transform: translateX(-50%);
  }
  .form {
    padding: 20px;
    h3 {
      text-align: center;
      margin-bottom: 20px;
    }
    .item {
      margin-top: 20px;
      .item-field {
        border-radius: 30px;
        background-color: #efefef;
      }
    }
  }
  /deep/.van-uploader__input-wrapper {
    border-radius: 50%;
    img {
      width: 70px;
      height: 70px;
      border-radius: inherit;
    }
  }
}
</style>